<template>
  <div>
    <div>
      <Button type="primary" size="small" ghost
              @click="openModal">选择</Button>
      <Button type="error" size="small" ghost
              style="margin-left: 8px"
              @click="clearIcon">清除</Button>
    </div>
    <Icon v-if="selectedIcon && selectedIcon !== ''"
          :type="selectedIcon" size="32"></Icon>

    <Modal v-model="visible"
           title="选择图标"
           @on-cancel="closeModal"
           footer-hide
           :width="1420"
           :styles="{top: '20px'}">
      <div class="icons">
        <div v-for="(item, index) in icons" :key="index"
             :class="[
               'icons-item',
               item.selected ? 'selected' : ''
             ]">
          <Icon :type="item.icon" size="36" color="#808695"
                @click.native="handleIconSelected(item, index)"/>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import Icons from '../../../../data/icons';

export default {
  name: 'iconSelector',
  props: {
    value: String
  },
  data() {
    return {
      visible: false,
      icons: Icons.icons,
      selectedIcon: this.value,
    };
  },
  methods: {
    openModal() {
      this.visible = true;
    },
    handleIconSelected(item, index) {
      this.$lodash.forEach(this.icons, (item) => {
        item.selected = false;
      });
      item.selected = true;
      this.$set(this.icons, index, item);
      this.selectedIcon = item.icon;

      this.$emit('input', this.selectedIcon);
      this.$emit('change', this.selectedIcon);
    },
    clearIcon() {
      this.selectedIcon = undefined;
      this.$lodash.forEach(this.icons, (item) => {
        item.selected = false;
      });

      this.$emit('input', this.selectedIcon);
      this.$emit('change', this.selectedIcon);
    },
    closeModal() {
      this.visible = false;
    }
  },
  watch: {
    value(val) {
      this.selectedIcon = val;
      this.$lodash.forEach(this.icons, (item) => {
        item.selected = false;
      });
      const selected = this.$lodash.find(this.icons, item => item.icon === this.selectedIcon);
      if (selected) {
        selected.selected = true;
      }
    }
  }
};
</script>

<style scoped lang="less">
  .icons {
    overflow: hidden;
    zoom: 1;
    text-align: center;
  }
  .icons-item {
    float: left;
    margin: 6px 6px 6px 6px;
    width: 48px;
    text-align: center;
    list-style: none;
    cursor: pointer;
    height: 48px;
    line-height: 45px;
    position: relative;
  }
  .selected {
    border: 1px solid #B72024
  }
</style>
